﻿using System;
using System.Diagnostics;
using System.Net.Mail;
using System.Text;

namespace Smart.Loggers
{
	public class EmailProvider : ILoggerProvider
	{
		/// <summary>
		/// The higher the value, the most important provider is
		/// </summary>
		public int Priority { get { return 10; } }

		/// <summary>
		/// Minimal severity to log
		/// </summary>
		public MessageSeverity MinimalSeverity { get { return MessageSeverity.Trace; } }

		public string SmtpHost { get; set; }
		public string SmtpFrom { get; set; }
		public string SmtpTo { get; set; }
		public string MailSubject { get; set; }

		[ThreadStatic]
		public static SmtpClient Client;

		/// <summary>
		/// Log function
		/// </summary>
		public void Log(string category, MessageSeverity severity, string module, string message, Exception x, string fullMessage)
		{
			try
			{
				var client = Client;

				if (client == null)
					Client = client = new SmtpClient(SmtpHost);

				if (!String.Equals(client.Host, SmtpHost))
				{
					Trace.WriteLine("EmailProvider.Log: provider uses caching, changes to SmtpHost breaking the cache!");
					Client = client = new SmtpClient(SmtpHost);
				}

				var mail =
					new MailMessage(SmtpFrom, SmtpTo)
					{
						SubjectEncoding = Encoding.UTF8,
						BodyEncoding = Encoding.UTF8,

						Priority = MailPriority.High,

						Subject = MailSubject,
						Body = fullMessage,
					};

				client.Send(mail);
			}
			catch (Exception ix)
			{
				Trace.WriteLine("EmailProvider.Log." + ix.GetType().Name + ": failed to send email message, " + ix.Message);
			}
		}
	}
}
